//
//  BaseWebController.swift
//  testZD
//
//  Created by 湛亚磊 on 2020/9/22.
//  Copyright © 2020 湛亚磊. All rights reserved.
//

import UIKit
import WebKit
import JavaScriptCore


public enum WebVCType:Int {
    /// 有头部
    case haveTopBar=1
    /// 无头部
    case noTopBar=2
}
open class BaseWebController: UIViewController {
    public var linkAddress:String = ""
    public var jumpType:WebVCType = .haveTopBar
    private var webViewISScal=true
    
    ///webview
    private lazy var webViewM: WKWebView = {
        let webViewM=WKWebView(frame: CGRect(x: 0, y: NAVBAR_HEIGHT, width: ScreenW, height: ScreenH-NAVBAR_HEIGHT), configuration: wkWebConfig)
        webViewM.scrollView.isScrollEnabled=true
        webViewM.scrollView.isUserInteractionEnabled=true
        webViewM.navigationDelegate = self
        webViewM.scrollView.delegate = self
        return webViewM
    }()
    
    /// 通信桥梁
    private var bridge:WebViewJavascriptBridge!
    
    /// web的配置
    private var wkWebConfig:WKWebViewConfiguration{
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.preferences.javaScriptEnabled = true
        ///禁止长按
        let jScriptLongClick : String="document.documentElement.style.webkitTouchCallout='none';"
        let wkUScriptLongClick = WKUserScript(source: jScriptLongClick, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        ///z禁止选择
        let jScriptChoise : String="document.documentElement.style.webkitUserSelect='none';"
        let wkUScriptChoise = WKUserScript(source: jScriptChoise, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        ///文字图片自适应
        let jScriptScal : String="var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}"
        let wkUScriptScal = WKUserScript(source: jScriptScal, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        
        let wkUController=WKUserContentController()
        wkUController.addUserScript(wkUScriptLongClick)
        wkUController.addUserScript(wkUScriptChoise)
        wkUController.addUserScript(wkUScriptScal)
        wkWebConfig.userContentController = wkUController
        wkWebConfig.allowsInlineMediaPlayback=true
        wkWebConfig.allowsAirPlayForMediaPlayback=true
        wkWebConfig.allowsPictureInPictureMediaPlayback=true
        return wkWebConfig
    }
    
    private lazy var progressView = UIProgressView.init(frame: CGRect(x: CGFloat(0), y: CGFloat(NAVBAR_HEIGHT), width: UIScreen.main.bounds.width, height: 2)).then {
        $0.tintColor = UIColor.green    // 进度条颜色
        $0.trackTintColor = UIColor.white // 进度条背景色
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(webViewM)
        self.view.addSubview(progressView)
        updateWebFrame()
        setData()
        setBridge()
    }
    
    
    /// 更新web的frame
    private func updateWebFrame()  {
        if jumpType == .noTopBar{
            webViewM.frame = CGRect(x: 0, y: 0, width: ScreenW, height: ScreenH)
            webViewM.size.height=ScreenH+NAVBAR_HEIGHT-STATUSBAR_HEIGHT
        }else{
            webViewM.size.height=ScreenH-NAVBAR_HEIGHT
        }
    }
    
    /// 设置通信的方法
    private func setBridge()  {
        //注册方法，js可以调用注册过后的方法
        bridge=WebViewJavascriptBridge(for: webViewM, showJSconsole: false, enableLogging: true)
        /// 日志
        bridge.registerHandler("logger") {(data, callback) in
            let newId:String = data as? String ?? ""
            print("日志信息--->>>\(newId)")
        }
        ///h5路由到达了跟路由
        bridge.registerHandler("APPPOP") { [weak self](data, callback) in
            self?.navigationController?.popViewController(animated: true)
        }
    }
    
    /// 开始调用
    private func setData()  {
        if linkAddress == ""{
            return
        }
        if let tempUrl=URL(string: linkAddress){
            ToastView.instance.showLoadingView()
            webViewM.load(URLRequest(url: tempUrl, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 3000))
        }else{
            
        }
        self.webViewM.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }
    
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    deinit {
        self.webViewM.removeObserver(self, forKeyPath: "estimatedProgress")
        self.webViewM.uiDelegate = nil
        self.webViewM.navigationDelegate = nil
    }
}

extension BaseWebController:WKNavigationDelegate,UIScrollViewDelegate {
    
    /// 监听加载进度
    public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //  加载进度条
        if keyPath == "estimatedProgress"{
            progressView.alpha = 1.0
            progressView.setProgress(Float((self.webViewM.estimatedProgress)), animated: true)
            print("加载的进度==>>\(self.webViewM.estimatedProgress)")
            if (self.webViewM.estimatedProgress)  >= 1.0 {
                ToastView.instance.clear()
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {[weak self] in
                    self?.progressView.alpha = 0
                    }, completion: {[weak self] (finish) in
                        self?.progressView.setProgress(0.0, animated: false)
                })
            }
        }
    }
    
    /// 加载完毕
    open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("h5加载完成",webView.url as Any)
        ToastView.instance.clear()
        webViewISScal=false
    }
    
    /// 缩放
    public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        if webViewISScal {
            return nil
        }else{
            return webViewM.scrollView.subviews[0]
        }
    }
}
